import {
  WxSetStorageSync,
  wxLogin,
  wxGetStorageSync,
  wxGetLocation,
  checkSession,
  wxRemoveStorageSync,
} from '../../utils/WxApiUtils'
import { apiMiniAppLogin, apiGetUserInfo, apiSaveUserInfo, apiInitUserLocation } from '../../api/login'
// import { getInfo } from '../../api/user'
import { validResp, isNullStr } from '../../utils/Validate'
import { fusingFn, AuthStepType } from '../../utils/Lang'
import { ACCESS_TOKEN, AVATAR, SHOP_ID, SHOP_NAME, NAME, IS_LOCATION, SHOP_TYPE, USER_TYPE, PHONE } from '../mutation-types'
export const fusing = fusingFn({ tryTimes: 1, restoreTime: 10000, name: 'refreshLogin' })

/**
 * 服务端解密用户信息
 */
// async function decodeUserInfo(rawUser) {
//   const param = {
//     rawData: rawUser.rawData,
//     signature: rawUser.signature,
//     encryptedData: rawUser.encryptedData,
//     iv: rawUser.iv,
//   }
//   console.log('解密param', param)
//   const resp = await apiGetUserInfo(param)
//   if (resp) return resp.data.model
//   else return null
// }

const user = {
  state: {
    status: '',
    token: wxGetStorageSync(ACCESS_TOKEN),
    name: wxGetStorageSync(NAME),
    avatar: '',
    isLocation: wxGetStorageSync(IS_LOCATION),
    shopId: wxGetStorageSync(SHOP_ID) || 0,
    shopName: wxGetStorageSync(SHOP_NAME),
    shopType: wxGetStorageSync(SHOP_TYPE),
    shopConfig: {},
    userType: wxGetStorageSync(USER_TYPE),
    phone: wxGetStorageSync(PHONE),
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ISLOCATION: (state, isLocation) => {
      state.isLocation = isLocation
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    // SET_CODE: (state, code) => {
    //   state.code = code
    // },
    // SET_USER: (state, user) => {
    //   state.user = user
    // },
    SET_SHOP_ID: (state, shopId) => {
      state.shopId = shopId
    },
    SET_SHOP_NAME: (state, shopName) => {
      state.shopName = shopName
    },
    SET_SHOP_TYPE: (state, shopType) => {
      state.shopType = shopType
    },
    SET_SHOP_CONFIG: (state, shopConfig) => {
      state.shopConfig = shopConfig
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone
    },
  },
  actions: {
    async LoginByPhone({ dispatch }, preload) {
      return new Promise(async (resolve, reject) => {
        try {
          const result = await dispatch('getOpenData', preload.cloudID)
          preload.phone = preload.phone || result.openData.data.phoneNumber
          preload.bizUserId = result.userInfo.openId
          preload.type = 1
          const loginResult = await dispatch('getUserInfo', preload)
          if (loginResult) {
            await dispatch('refreshLogin')
            // 记录登录状态
            // WxSetStorageSync('isLogin', true)
            resolve()
          } else {
            reject(new Error('登录失败'))
          }
        } catch (error) {
          reject(error)
          // wxRedirect('/pages/login/login')
        }
      })
    },
    getOpenData({ commit }, cloudID) {
      return new Promise((resolve, reject) => {
        wx.cloud
          .callFunction({
            name: 'getopendata',
            data: {
              openData: wx.cloud.CloudID(cloudID),
            },
          })
          .then(async (res) => {
            if (res.result.openData.errMsg) {
              reject(new Error(res.result.openData.errMsg))
              return
            }
            resolve(res.result)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 点击登录后去后台拿到token 返回
     */
    async doLogin({ commit }) {
      // 调用wx.checkSession判断session_key是否过期
      const hasSession = await checkSession()
      console.log('hasSession', hasSession)
      // 本地已有可用登录态且session_key未过期，resolve。
      if (wxGetStorageSync(ACCESS_TOKEN) && hasSession) return true

      const code = await wxLogin()
      console.log('code', code)
      const result = await apiMiniAppLogin(code)
      console.log('[获得token结果]', result)
      if (validResp(result)) {
        WxSetStorageSync(ACCESS_TOKEN, 'bearer' + result.data.access_token)
        commit('SET_TOKEN', 'bearer' + result.data.access_token)
        WxSetStorageSync('isLogin', true)
        return true
      }
      return false
    },
    async refreshLogin({ commit, dispatch }) {
      try {
        // 熔断
        await fusing()
        // 清除 Session
        commit('SET_TOKEN', '')
        wxRemoveStorageSync(ACCESS_TOKEN)
        WxSetStorageSync('isLogin', false)

        await dispatch('doLogin')
      } catch (error) {
        throw error
      }
    },
    /**
     * 获取用户信息
     */
    async getUserInfo({ commit }, preload) {
      console.log('getUserInfo', preload)
      const resp = await apiGetUserInfo(preload)
      console.log('getUserInfo resp', resp)
      if (validResp(resp)) {
        const weixinUser = resp.data.model
        console.log('保存后的用户', weixinUser)
        if (!weixinUser) return false
        WxSetStorageSync(NAME, weixinUser.nickName)
        WxSetStorageSync(AVATAR, weixinUser.avatar)
        WxSetStorageSync(IS_LOCATION, !!weixinUser.userLat)
        WxSetStorageSync(USER_TYPE, weixinUser.userType)
        WxSetStorageSync(PHONE, weixinUser.phone)
        WxSetStorageSync(SHOP_ID, weixinUser.shopId)
        // WxSetStorageSync(SHOP_NAME, result.shop ? result.shop.name : '')
        commit('SET_NAME', weixinUser.nickName)
        commit('SET_AVATAR', weixinUser.avatar)
        commit('SET_ISLOCATION', !!weixinUser.userLat)
        commit('SET_USER_TYPE', weixinUser.userType)
        commit('SET_PHONE', weixinUser.phone)
        commit('SET_SHOP_ID', weixinUser.shopId)
        // commit('SET_SHOP_NAME', result.shop ? result.shop.name : '')
        return true
      }
      return false
    },
    /**
     * 保存用户信息
     */
    saveUserInfo({ commit }, rawUser) {
      // const rawUser = await wxGetUserInfo()
      console.log('[用户信息]', rawUser)
      apiSaveUserInfo(rawUser).then((resp) => {
        if (validResp(resp)) {
          const weixinUser = resp.data.model
          console.log('保存后的用户', weixinUser)
          if (!weixinUser) return false
          WxSetStorageSync(IS_LOCATION, !!weixinUser.userLat)
          WxSetStorageSync(USER_TYPE, weixinUser.userType)
          WxSetStorageSync(PHONE, weixinUser.phone)
          // commit("SET_USER",weixinUser);
          commit('SET_ISLOCATION', !!weixinUser.userLat)
          commit('SET_USER_TYPE', weixinUser.userType)
          commit('SET_PHONE', weixinUser.phone)
        }
      })
      WxSetStorageSync(NAME, rawUser.nickName)
      WxSetStorageSync(AVATAR, rawUser.avatar)
      commit('SET_NAME', rawUser.nickName)
      commit('SET_AVATAR', rawUser.avatar)
      return true
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        wxRemoveStorageSync(NAME)
        wxRemoveStorageSync(AVATAR)
        wxRemoveStorageSync(IS_LOCATION)
        wxRemoveStorageSync('isLogin')
        resolve()
      })
    },

    // 登出
    RegFinish({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        wxRemoveStorageSync(NAME)
        wxRemoveStorageSync(AVATAR)
        wxRemoveStorageSync(IS_LOCATION)
        wxRemoveStorageSync('isLogin')
        resolve()
      })
    },

    initLocation({ commit }) {
      return new Promise((resolve, reject) => {
        wxGetLocation()
          .then((res) => {
            console.log('[wxGetLocation]', res)
            if (res.errMsg === 'getLocation:ok') {
              WxSetStorageSync('userLat', res.latitude)
              WxSetStorageSync('userLng', res.longitude)
              commit('SET_ISLOCATION', true)
              WxSetStorageSync('isLocation', true)
              if (wxGetStorageSync('token') && res.longitude) {
                apiInitUserLocation({
                  userLat: res.latitude,
                  userLng: res.longitude,
                }).then((resp) => {})
              }
            }
          })
          .catch((err) => {
            reject(err)
          })
          .finally(() => {
            resolve()
          })
      })
    },
  },
}

export default user
